<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/10/12
 * Time: 10:58
 */

namespace app\api\controller;


use language\Languagemsg;
use pay\Ali;
use pay\Wx;
use think\Db;

class Shop extends Base
{
    private $user_id; // 用户ID
    private $page; // 页码
    private $create_time;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->msg_language = new Languagemsg();
        $this->language = input('language') ? input('language') : 0;
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301, 'msg'=>$this->msg_language->otherLogin[$this->language]]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->msg_language->frost[$this->language]]);
            exit;
        }
    }
    
    /**
     * 保存/编辑店铺基本信息
     * @return \think\response\Json
     * shop_name        店铺名称
     * shop_logo        店铺LOGO
     * shop_goods_type  主营商品种类
     * shop_intro       店铺简介
     * shop_images      店铺图片
     */
    public function saveShopInfo(){
        $shop_name = input('shop_name');
        $shop_logo = input('shop_logo');
        $shop_goods_type = input('shop_goods_type');
        $shop_intro = input('shop_intro');
        $shop_images = input('shop_images');
        $data = [
            'shop_name' => $shop_name,
            'shop_logo' => $shop_logo,
            'shop_goods_type' => $shop_goods_type,
            'shop_intro' => $shop_intro,
            'shop_images' => $shop_images,
            'shop_update_time' => $this->create_time
        ];
        $res = Db::table('up_shop')->where('shop_user_id', $this->user_id)->update($data);
        if($res){
//            return json(['status' => 200, 'msg' => '保存成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->saveSuccess[$this->language]]);
        }else{
//            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
            return json(['status' => 0, 'msg' => $this->msg_language->systemErr[$this->language]]);
        }
    }
    
    /**
     * 店铺基本信息
     * @return \think\response\Json
     */
    public function shopBaseInfo(){
        $info = Db::table('up_shop')
            ->where('shop_user_id', $this->user_id)
            ->field('shop_id, shop_name, shop_logo, shop_goods_type, shop_intro, shop_images')
            ->find();
        if($info){
            $shop_goods_type = Db::table('up_goods_type')
                ->where('gt_id', 'IN', $info['shop_goods_type'])
                ->where('gt_del', 1)
                ->column('gt_name');
            $info['shop_goods_type_name'] = implode(',', $shop_goods_type);
            return json(['status' => 200, 'msg' => $info]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 可选主营商品种类的个数
     * @return \think\response\Json
     */
    public function goodsTypeNum(){
        $num = Db::table('up_other')->where('other_id', 8)->value('other_goods_num');
        return json(['status' => 200, 'msg' => $num]);
    }
    
    /**
     * 店铺评价
     * @return \think\response\Json
     * page     页码
     */
    public function shopComment(){
        // 店铺下所有上架商品
        $goods_ids = $this->shopGoodsIds();
        if($goods_ids){
            // 所有商品的评价
            $comment = Db::table('up_goods_comment')
                ->join('up_u_user', 'user_id = gc_user_id', 'left')
                ->where('gc_goods_id', 'IN', $goods_ids)
                ->field('user_username, user_image, gc_time, gc_content, gc_images')
                ->order('gc_time desc')
                ->page($this->page, 15)
                ->select();
            if($comment){
                foreach($comment as $k => $v){
                    if($v['gc_images']){
                        $gc_images = trim($v['gc_images'], ',');
                        $comment[$k]['gc_images'] = explode(',', $gc_images);
                    }else{
                        $comment[$k]['gc_images'] = [];
                    }
                }
                return json(['status' => 200, 'msg' => $comment]);
            }else{
                return json(['status' => 200, 'msg' => []]);
            }
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
        
    }
    
    /**
     * 今日统计
     * @return \think\response\Json
     */
    public function todayCount(){
        $date = date('Y-m-d');
        $goods_ids = $this->shopGoodsIds();
        // 余额
        $balance = Db::table('up_u_user')->where('user_id', $this->user_id)->value('user_balance');
        $count = ['today_price' => 0, 'order_num' => 0, 'goods_num' => 0, 'look_num' => 0, 'user_balance' => $balance];
        if($goods_ids){
            $orderCount = Db::table('up_goods_order')
                ->where('order_sail_user_id', $this->user_id)
                ->where('order_status', 'IN', '2,3,4,9')
                ->where('order_pay_date', $date)
                ->field('sum(order_pay_price) today_price, count(order_id) order_num, sum(order_num) goods_num')
                ->find();
            $look_num = Db::table('up_goods')
                ->where('goods_id', 'IN', $goods_ids)
                ->field('sum(goods_look_num) look_num')
                ->find();
            if($orderCount['today_price']) $count['today_price'] = $orderCount['today_price'];
            if($orderCount['order_num']) $count['order_num'] = $orderCount['order_num'];
            if($orderCount['goods_num']) $count['goods_num'] = $orderCount['goods_num'];
            if($look_num) $count['look_num'] = $look_num['look_num'];
        }
        return json(['status' => 200, 'msg' => $count]);
    }
    
    /**
     * 资产管理
     * @return \think\response\Json
     */
    public function ziChang(){
        $date = date('Y-m-d');
        $seven_days_ago = date('Y-m-d', strtotime('-7 days'));
        $data = Db::table('up_goods_order')
            ->where('order_pay_date', 'between', [$seven_days_ago, $date])
            ->where('order_status', 'IN', '2,3,4,5,7,9')
            ->where('order_sail_user_id', $this->user_id)
            ->field('sum(order_pay_price) day_price, order_pay_date')
            ->order('order_pay_date asc')
            ->group('order_pay_date')
            ->select();
        $dateArr = []; // 日期
        $priceArr = []; // 金额
        $total_price = 0; // 近7天总营收
        if($data){
            $dateArr = array_column($data, 'order_pay_date');
            $priceArr = array_column($data, 'day_price');
            $total_price = array_sum($priceArr);
        }
        return json(['status' => 200, 'msg' => '', 'dateArr' => $dateArr, 'priceArr' => $priceArr, 'total_price' => $total_price]);
    }
    
    /**
     * 收支明细
     * @return \think\response\Json
     */
    public function buySail(){
        $data = Db::table('up_goods_order')
            ->where('order_status', 'NEQ', 1)
            ->where(function ($query){
                $query->where('order_buy_user_id', $this->user_id)
                    ->whereOr('order_sail_user_id', $this->user_id);
            })
            ->field('order_id, order_buy_user_id, order_sail_user_id, order_pay_type, order_pay_price, 
            order_pay_time')
            ->page($this->page, 15)
            ->order('order_pay_time desc')
            ->select();
        if($data){
            foreach($data as $k => $v){
                if($v['order_buy_user_id'] == $this->user_id){
                    $data[$k]['type'] = 1; // 支出
                }
                if($v['order_sail_user_id'] == $this->user_id){
                    $data[$k]['type'] = 2; // 收入
                }
            }
            return json(['status' => 200, 'msg' => $data]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 收支明细详情
     * @return \think\response\Json
     * order_id       订单ID
     */
    public function buySailDetail(){
        $order_id = input('order_id');
        $detail = Db::table('up_goods_order')
            ->where('order_id', $order_id)
            ->field('order_pay_time, order_status, order_pay_price, order_number, order_pay_type, 
            order_buy_user_id, order_sail_user_id')
            ->find();
        if($detail['order_buy_user_id'] == $this->user_id){
            $detail['order_other_user_name'] = Db::table('up_u_user')
                ->where('user_id', $detail['order_sail_user_id'])
                ->value('user_username');
            $detail['type'] = 1; // 支出
        }
        if($detail['order_sail_user_id'] == $this->user_id){
            $detail['order_other_user_name'] = Db::table('up_u_user')
                ->where('user_id', $detail['order_buy_user_id'])
                ->value('user_username');
            $detail['type'] = 2; //收入
        }
        return json(['status' => 200, 'msg' => $detail]);
    }
    
    /**
     * 店铺下所有商品
     * @return array
     */
    private function shopGoodsIds(){
        $goods_ids = Db::table('up_goods')
            ->where('goods_user_id', $this->user_id)
            ->where('goods_status', 1)
            ->column('goods_id');
        return $goods_ids;
    }
    
    /**
     * 用户余额
     * @return \think\response\Json
     */
    public function userBalance(){
        $balance = Db::table('up_u_user')->where('user_id', $this->user_id)->value('user_balance');
        return json(['status' => 200, 'msg' => $balance]);
    }
    
    /**
     * 余额明细
     * @return \think\response\Json
     * page    页码
     */
    public function balanceDetail(){
        $list = Db::table('up_balance_detail')
            ->join('up_goods_order', 'bd_order_id = order_id', 'LEFT')
            ->join('up_goods', 'order_goods_id = goods_id', 'LEFT')
            ->where('bd_user_id', $this->user_id)
            ->field('goods_name, bd_price, bd_type, bd_tixian_type, bd_time, order_number')
            ->page($this->page, 15)
            ->order('bd_time desc')
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 设置交易密码
     * @return \think\response\Json
     * phone        手机号
     * code         验证码
     * pwd          密码
     * affirm_pwd   确认密码
     */
    public function setTiXianPassword(){
        $phone = input('phone');
        $code = input('code');
        $pwd = input('pwd');
        $affirm_pwd = input('affirm_pwd');
        
//        if(!$phone) return json(['status' => 0, 'msg' => '请输入手机号']);
//        if(!$code) return json(['status' => 0, 'msg' => '请填写验证码']);
//        if(!$pwd) return json(['status' => 0, 'msg' => '请填写密码']);
//        if(!$affirm_pwd) return json(['status' => 0, 'msg' => '请确认密码']);
//        if($pwd !== $affirm_pwd) return json(['status' => 0, 'msg' => '密码不一致']);
        if(!$phone) return json(['status' => 0, 'msg' => $this->msg_language->writePhone[$this->language]]);
        if(!$code) return json(['status' => 0, 'msg' => $this->msg_language->writeYZM[$this->language]]);
        if(!$pwd) return json(['status' => 0, 'msg' => $this->msg_language->writepwd[$this->language]]);
        if(!$affirm_pwd) return json(['status' => 0, 'msg' => $this->msg_language->affirmpwd[$this->language]]);
        if($pwd !== $affirm_pwd) return json(['status' => 0, 'msg' => $this->msg_language->pwdNotSame[$this->language]]);
    
        // 验证码
        $yzm = Db::table('up_phonecode')->where('phone', $phone)->where('check_type', 1)->order('time desc')->limit(1)->find();
//        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => $this->msg_language->yzmErr[$this->language]]);
        // 5分钟超时
        $now = time();
//        if($now - $yzm['time'] > 300) return json(['status' => 0, 'msg' => '验证码失效']);
//        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码已使用']);
        if($now - $yzm['time'] > 300) return json(['status' => 0, 'msg' => $this->msg_language->yzmLose[$this->language]]);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => $this->msg_language->yzmUsed[$this->language]]);
        
        $update = [
            'user_jy_password' => md5($pwd),
            'user_update_time' => $this->create_time
        ];
        
        $res = Db::table('up_u_user')->where('user_id', $this->user_id)->update($update);
        if($res){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
//            return json(['status' => 200, 'msg' => '设置成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->setSuccess[$this->language]]);
        }else{
//            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
            return json(['status' => 0, 'msg' => $this->msg_language->systemErr[$this->language]]);
        }
    }
    
    /**
     * 提现
     * @return \think\response\Json
     * tx_price        提现金额
     * tx_type         提现类型    1 银联    2 支付宝   3 微信
     * tx_pwd          交易密码
     * tx_account      微信/支付宝账号
     * tx_real_name    真实姓名
     * tx_openid       微信提现openid
     */
    public function tiXian(){
        $tx_price = input('tx_price');
        $tx_type = input('tx_type'); // 1 银联   2 支付宝   3 微信
        $tx_pwd = input('tx_pwd');
        $tx_account = input('tx_account'); // 微信/支付宝账号
        $tx_real_name = input('tx_real_name'); // 真实姓名
        $tx_openid = input('tx_openid'); // 微信提现openid
        $order_number = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT); // 订单号
    
        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_balance, user_jy_password')->find();
        
        // 余额判断
//        if($tx_price > $user['user_balance']) return json(['status' => 0, 'msg' => '账户余额不足']);
        if($tx_price > $user['user_balance']) return json(['status' => 0, 'msg' => $this->msg_language->balanceLose[$this->language]]);
        
        // 交易密码
//        if(md5($tx_pwd) != $user['user_jy_password']) return json(['status' => 0, 'msg' => '交易密码错误']);
        if(md5($tx_pwd) != $user['user_jy_password']) return json(['status' => 0, 'msg' => $this->msg_language->jyPwdErr[$this->language]]);
        
        // 订单
        $order = [
            'bo_number' => $order_number,
            'bo_price' => $tx_price,
            'bo_type' => $tx_type,
            'bo_time' => $this->create_time
        ];
        
        if($tx_type == 1){
            // 用户是否有添加过银行卡
            $have_bank_card = Db::table('up_bank_card')
                ->where('bc_user_id', $this->user_id)
                ->where('bc_del', 1)
                ->find();
//            if(!$have_bank_card) return json(['status' => 0, 'msg' => '请先添加银行卡']);
            if(!$have_bank_card) return json(['status' => 0, 'msg' => $this->msg_language->addBankCard[$this->language]]);
            // TODO:银联提现
            
        }elseif($tx_type == 2){ // 支付宝提现
            $order['bo_account'] = $tx_account;
            $order['bo_real_name'] = $tx_real_name;
            
            $tx = ['out_biz_no' => $order_number, 'payee_account' => $tx_account, 'amount' => $tx_price, 'payee_real_name' => $tx_real_name];
            $ali = new Ali(config('ali'));
            $result = $ali->aliTiXian($tx);
        }else{ // 微信提现
            $order['bo_account'] = $tx_account;
            $order['bo_openid'] = $tx_openid;
            
            $wx = new Wx(config('weixin'));
            $result = $wx->wxTiXian($order_number, $tx_openid, $tx_price);
        }
        
        if($result['status'] == 200){
            Db::startTrans();
            try{
                // 提现订单表
                Db::table('up_balance_order')->insert($order);
                
                // 余额明细表
                $detail = [
                    'bd_user_id' => $this->user_id,
                    'bd_price' => $tx_price,
                    'bd_type' => 2,
                    'bd_tixian_type' => $tx_type,
                    'bd_time' => $this->create_time
                ];
                Db::table('up_balance_detail')->insert($detail);
                // 减用户余额
                Db::table('up_u_user')->where('user_id', $this->user_id)->setDec('user_balance', $tx_price);
                Db::commit();
//                return json(['status' => 200, 'msg' => '提现成功']);
                return json(['status' => 200, 'msg' => $this->msg_language->tiXianSuccess[$this->language]]);
            }catch(\Exception $e){
                Db::rollback();
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        }else{
            return json(['status' => 0, 'msg' => $result['msg']]);
        }
    }

}